package app.remote.common.Rss;

import app.remote.entity.RssTorrent;
import app.remote.entity.RssUrl;
import app.remote.entity.TorrentAddRequest;
import app.remote.entity.TorrentList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.ResultSet;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: haibo.wang
 * Date: 13-7-10
 * Time: 下午5:19
 * To change this template use File | Settings | File Templates.
 */
@Component
public class WebService {
    private final Log log = LogFactory.getLog(WebService.class);
    private final String remoteUrl = "http:192.168.1.200:9091/transmission/rpc";

    private List<RssUrl> urls;

    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private RestTemplate restTemplate;
    /*@Resource
    private HttpHeaders httpHeaders;*/

    public WebService() {
    }

    @PostConstruct
    public void init() {
        urls = jdbcTemplate.query("select * from rss_url", (ResultSet rs, int i) -> {
            RssUrl url = new RssUrl();
            url.setId(rs.getInt("id"));
            url.setName(rs.getString("name"));
            url.setUrl(rs.getString("url"));
            url.setLocation(rs.getString("location"));
            return url;
        });
    }

    @Scheduled(cron="30/30 * *  * * ? ")
    public void readTorrent() {
        TorrentList torrentList = restTemplate.getForObject("http://wanghaibo.duapp.com/transmission/web/torrent", TorrentList.class);
        torrentList.getTorrents().forEach((RssTorrent e) -> {
            TorrentAddRequest request = createRequestEntity(e);
            /*HttpEntity<Object> requestEntity = new HttpEntity<Object>(request, httpHeaders);
            restTemplate.put(remoteUrl, requestEntity);*/
        });
    }

    private TorrentAddRequest createRequestEntity(RssTorrent torrent) {
        TorrentAddRequest request = new TorrentAddRequest();
        request.getArguments().put("filename", torrent.getUrl());
        request.getArguments().put("download-dir", torrent.getLocation());
        request.getArguments().put("peer-limit", 60);
        return request;
    }
}
